package com.shop.model.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shop.model.entity.GoodsTb;
import com.shop.model.entity.ShopcartTb;
import com.shop.model.service.IGoodsTbService;
import com.shop.model.service.IOrderTbService;
import com.shop.model.service.IShopcartTbService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;

@Controller
public class AliController {
    private  final String APP_ID="2016092300576700";
    //自己生成的私钥
    private  final String APP_PRIVATE_KEY="MIIEwAIBADANBgkqhkiG9w0BAQEFAASCBKowggSmAgEAAoIBAQCxSB0eFXRefYkVGqANRsiinoqt+OVr0YnoC1dQ3OkRwP5MHAQ8q4+QYSSZaeENVXkq840uCOvTDdqM0jiP8Yen23BMe5IQVuzMJWYdWNVupczRrG4dyZa4DGNv2+nm5FB/aPOv3L3XwAKboPl4AkFGyPO62hDPZSipO9ZS2FExWwjFWfUPj/nKcAeYNOUjeyE98Rn1YoVYZxFf32CvOA8HtChwHoM/zq1B1H80JBMsEJsGQmCze0AvjJ//7g+9fHEggM5Va2+eGHwNGP27/E9POxj9ex3bxUKMnPTAdtf8E0iXlAle3qYGBR8k2Ru9JBU9MvICqUA671p0CQHmxoThAgMBAAECggEBAKLCGjlsaRH3HsuJTjfiLIFgHOHsCHUcQwgOoXNT3Ya3MMCfWCR7ParIBNn0IvIi7sNIJu2Esz1pEqUGu3crv+eTx13wdQEbTPt/umhnDkwvXAOD0vT2BrGibghcVjnskxrmOBPVDVXuqnZHK8HKEDP0eg+p9JTzwojcrsAQaTptWXKoxmdSOY8QFtfs0vcgh+sL+SzzJRptmHQ10DQzNkCxUFU4kNEwfHBGVgntZWATvLeJ95h5SXh4iZHr9ChDLAMdCyGblts5jsPXg9t1PZxH44/ed/xb28FoPN9jQLaKgRahf+anWLB1KOi8LD2uZ98jt6o5d1XsvW5QMDilwYECgYEA44tn6iEJEuUayLX8GxtzVzx7f7uF0ia+tjnIx2/IFxpIU5BLDybEfPmPjIgGyOkCnwRS+vvDa8zpLRlR8t9elPt6pzjYr7nKWziJ46Az67wWkGqrH//ZfZrfhNnFWXvnW55SyauQjMPQrof+EXgEag0PyEF3JIizdHLKtFf+Ul0CgYEAx3OYsDhRmDp9NxbCzRP2gHflKT/4d12OIm8KBRJbQ04XT4248jw6xV2Zb//Mn3hJDdRdI73XVy+bX4XQ8q009B1caaCuJfFfwGCqtUZ2N3R8Lpysw003mwVloFa++QepzMTTRzjfnTDaxyV2b8N2K3QqAoSASXIoNc+gRUhvHFUCgYEAwsabLeQXY1Av7C0zX3TQ95SzVnSLqYc26r9t6aH60iPSU42JYq/Zs+zf/viVbjde4gWOjn8iGc3ur4ckCdVAniDiLfBQM6PC3vD3v5xrtVdsrTRRxXN5lbYTrSHId7/DHD7bOPweIRChOjT4u7VTegAySUYYmXJWwtBcSaGk9pUCgYEAnoP62CMKhkgF+GB4lfDFuriPQsd6u7N5IVjKx9kc+1L3J9zlHnBL7UxEhETy5dL9jKY5GAzrNnm5rKN3u0d5jIJBThnMDo/Vn9m0ErpbfhtwDsOqctXN2cDiUhpfUSCMDRhpKnPDFPUdC6V0icL5CfQa50FTjAvUdV/8atP0qrkCgYEA2OIVnd9cewFYWLmmiglLgtNPQSZ1uGKsTRmWDUBqtmhm/K4D3QtHAJHhkiCpnrcsM1tSoU2rZSMhnslvQv3i1ukQ8pOLzfB22wOKEYlDLUGjhsJHza9bPDDEsEP0ZDwaZBzvZjXyi2nkisLDjEutA7wsesVLU5N+qFBeIvaEBjw=";
    private  final String FORMAT="json";
    private  final String CHARSET="UTF-8";
    //支付宝公钥
    private  final String ALIPAY_PUBLIC_KEY="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3FX+/+ADtO6d/2yiHyF3Wo0qWL7jqe+oJ4uFcV9IfUay9xiE1CRcDK3gKbgd6LTndIgVHkaB0IbPSkjmJcrLZ0YYVj6hz3RVcrRQw/byXDIM2ha1yQSeiwswjZR2cGpcBT/JjelwmvN71eZp3Ok6GTUXWv+CyIF6lNUVJpYoeAKFptGOeo49ttV9KHD0n/bdZVH9/6B522NTG7A277lHiVxuSTob5X7qjJYetoWfJTW3MnQTzN2ns521HUZe6oAvCcnaC4r9PwDVloMhHR+wb7hafh3Pj2+wst+z5fwRN91bhapwuqKYdeS+DsEj/2yu/XRBXkEyYR5w77JsEWUB+wIDAQAB";


    @Autowired
    private IGoodsTbService iGoodsTbService;

    @Autowired
    private IShopcartTbService iShopcartTbService;

    @Autowired
    private IOrderTbService iOrderTbService;

    @RequestMapping("/pay")
    public void aliPay(HttpServletRequest httpRequest,
                       HttpServletResponse httpResponse) throws ServletException, IOException {
        HttpSession session1 = httpRequest.getSession();
        int userId1 =(int) session1.getAttribute("userId");
        //System.out.println("这是session111111111"+userId1);

        if(null!=httpRequest.getParameter("goodsId")&&null!=httpRequest.getParameter("goodsNum")&&null!=httpRequest.getParameter("attributes")){
            // 说明这是针对商品详情页的购买 获取商品id  商品数量  商品属性
            //跳转订单controller需要传 订单编号集  订单描述集  订单编号集  所属用户 价格集  数量集
            //商品id 传
            System.out.println("------------lailedsdsds");
            String goodsId = httpRequest.getParameter("goodsId");
            //商品价格
            GoodsTb goodsTb = iGoodsTbService.getById(goodsId);
            BigDecimal price = goodsTb.getPrice();
            //商品数量  传
            String sgoodsNum = httpRequest.getParameter("goodsNum");
            Integer goodsNum = Integer.valueOf(sgoodsNum);
            BigDecimal big2 = new BigDecimal(goodsNum.toString());
            //商品小计
            BigDecimal multiply = price.multiply(big2);//multiply是BigDecimal的乘法运算
            //购买的属性  传
            String attributes = httpRequest.getParameter("attributes");
            //创建一个商品描述
            String goodsName = goodsTb.getGoodsName();
            String description=goodsName+"   "+attributes;

            //随机生成一个订单ID ，64个字符以内
            int r1=(int)(Math.random()*(10));//产生2个0-9的随机数
            int r2=(int)(Math.random()*(10));
            long now = System.currentTimeMillis();//一个13位的时间戳
            String orderID =String.valueOf(r1)+String.valueOf(r2)+String.valueOf(now);// 订单ID
            String orderNums =orderID;// 订单编号

            //成功后跳转页面。跳到详情页
            String returnUrl="http://bcd.free.idcfengye.com:8080/details?id="+goodsId;
            String place="no";
            //调方法传参数 String cartGoodsNums,String prices,String place,String ids,
            payUtil(sgoodsNum,price+"",place,goodsId+"",returnUrl,userId1,orderID,orderNums,multiply,description,httpRequest,httpResponse);
            //String returnUrl,int userId1, String orderId,String orderNums,BigDecimal sumPrice,String description,HttpServletRequest httpRequest, HttpServletResponse httpResponse

        }else{
            //针对购物车的购买
            //获取传过来的id信息  针对购物车
            if(null!=httpRequest.getParameter("ids")){
                String ids = httpRequest.getParameter("ids");
                String[] split = ids.split(",");
                String orderNums="";//将每个生成的订单编号拼接在这个上面，中间；隔开，到ordercontroller去遍历获取分别加订单
                //创建一个描述
                String description="";
                //价格集
                String prices="";
                //数量集
                String cartGoodsNums="";
                    //总价
                BigDecimal cartSubtotal=new BigDecimal("0");
                for(int i=0;i<split.length;i++){
                    if(i==split.length-1){
                        //说明是最后一个  拼接的时候不要加；
                        Integer shopCartId = Integer.valueOf(split[i]);
                        ShopcartTb shopcart_idTb = iShopcartTbService.getOne(new QueryWrapper<ShopcartTb>().eq("shopcart_id", shopCartId));
                        //数量
                        Integer cartGoodsNum = shopcart_idTb.getCartGoodsNum();
                        String cartGoodsAttribute = shopcart_idTb.getCartGoodsAttributeId();//属性
                        Integer cartGoodsId = shopcart_idTb.getCartGoodsId();
                        GoodsTb goods = iGoodsTbService.getOne(new QueryWrapper<GoodsTb>().eq("goods_id", cartGoodsId));
                        String goodsName = goods.getGoodsDescribe();
                        //创建一个描述
                        description=description+goodsName+" "+cartGoodsNum+"   "+cartGoodsAttribute;
                        BigDecimal price = shopcart_idTb.getCartSubtotal();
                        prices=prices+price;
                        //价格
                        cartSubtotal = price.add(cartSubtotal);
                        //数量集
                        cartGoodsNums=cartGoodsNums+cartGoodsNum;

                        //随机生成一个订单id，存在数组中
                        int r1=(int)(Math.random()*(10));//产生2个0-9的随机数
                        int r2=(int)(Math.random()*(10));
                        long now = System.currentTimeMillis();//一个13位的时间戳
                        orderNums =orderNums+String.valueOf(r1)+String.valueOf(r2)+String.valueOf(now);// 订单ID
                    }else {
                        Integer shopCartId = Integer.valueOf(split[i]);
                        ShopcartTb shopcart_idTb = iShopcartTbService.getOne(new QueryWrapper<ShopcartTb>().eq("shopcart_id", shopCartId));
                        //数量
                        Integer cartGoodsNum = shopcart_idTb.getCartGoodsNum();
                        String cartGoodsAttribute = shopcart_idTb.getCartGoodsAttributeId();//属性
                        Integer cartGoodsId = shopcart_idTb.getCartGoodsId();
                        GoodsTb goods = iGoodsTbService.getOne(new QueryWrapper<GoodsTb>().eq("goods_id", cartGoodsId));
                        String goodsName = goods.getGoodsDescribe();
                        //创建一个描述
                        description=description+goodsName+" "+cartGoodsNum+"   "+cartGoodsAttribute+";";
                        BigDecimal price = shopcart_idTb.getCartSubtotal();
                        prices=prices+price+";";
                        //价格
                        cartSubtotal = price.add(cartSubtotal);
                        //数量集
                        cartGoodsNums=cartGoodsNums+cartGoodsNum+";";

                        //随机生成一个订单id，存在数组中
                        int r1=(int)(Math.random()*(10));//产生2个0-9的随机数
                        int r2=(int)(Math.random()*(10));
                        long now = System.currentTimeMillis();//一个13位的时间戳
                        orderNums =orderNums+String.valueOf(r1)+String.valueOf(r2)+String.valueOf(now)+";";// 订单ID
                    }

                }

                //随机生成一个订单id,用于创建支付 无实际意义
                int r1=(int)(Math.random()*(10));//产生2个0-9的随机数
                int r2=(int)(Math.random()*(10));
                long now = System.currentTimeMillis();//一个13位的时间戳
                String orderID =String.valueOf(r1)+String.valueOf(r2)+String.valueOf(now);// 订单ID
                String returnUrl="http://bcd.free.idcfengye.com:8080/showShopCart?userId="+userId1;
                //调方法传参数
                String place="shopCart";
                payUtil(cartGoodsNums,prices,place,ids,returnUrl,userId1,orderID,orderNums,cartSubtotal,description,httpRequest,httpResponse);

            }
        }

    }

    public void  payUtil(String cartGoodsNums,String prices,String place,String ids,String returnUrl,int userId1, String orderId,String orderNums,BigDecimal sumPrice,String description,HttpServletRequest httpRequest, HttpServletResponse httpResponse)throws IOException{
        System.out.println("来支付吧");
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do", APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, "RSA2"); //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
        //支付成功后跳转页面
        alipayRequest.setReturnUrl(returnUrl);
        //异步跳转的后台
        alipayRequest.setNotifyUrl(" http://yachen.free.idcfengye.com/addOrder?userId="+userId1+"&description="+description+"&orderNums="+orderNums+"&ids="+ids+"&place="+place+"&prices="+prices+"&cartGoodsNums="+cartGoodsNums);//在公共参数中设置回跳和通知地址
        System.out.println("这是构建表单的一系列数据：");
        System.out.println(cartGoodsNums+"----------"+prices+"----------"+place+"----------"+ids+"----------"+returnUrl+"----------"+userId1+"----------"+orderId+"----------"+orderNums+"----------"+sumPrice+"----------"+description);
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":\""+orderId+"\"," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "    \"total_amount\":"+sumPrice+"," +
                "    \"subject\":\""+description+"\"," +
                "    \"body\":\""+description+"\"," +
                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
                "    \"extend_params\":{" +
                "    \"sys_service_provider_id\":\"2088511833207846\"" +
                "    }"+
                "  }");//填充业务参数
        String form="";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
        System.out.println("结束了啊哈");
    }

}
